<?php

namespace App\Http\Controllers;

use App\Http\Controllers\Controller as BaseController;
use Illuminate\Http\Request;
use Excel;
use Illuminate\Support\Facades\Response;
use Validator;
use Session;
use App\Http\Models\CustomerModel;
use App\Http\Models\ArticleTypeModel;
use App\Http\Models\TypeDetailModel;

class AdminController extends BaseController
{
    
    public function login(Request $request)
    {
        if($request->isMethod('get')){
            return view('/admin/article/login');
        } else if($request->isMethod('post')){
            $data = $request->except('_token');
            $messages = [
                'required'   => '不能为空',
                'string'     => '格式错误',
            ];
            $validator = Validator::make($data, [
                'username'  => 'required|string',
                'password'  => 'required|string',
            ],$messages);
            if ($validator->fails()) {
                return redirect('/login')
                    ->withErrors($validator)
                    ->withInput($data);
            }
            $res = CustomerModel::where(['account'=>$data['username'],'password'=>md5($data['password'])])->first();
            if($res){
                session(['userid'=>$res->id]);
                session(['username'=>$res->member]);
                if(session('userid')) {
                    return redirect('/');
                } else {
                    return redirect('/login');
                }
            } else {
                $username='账号或者密码错误';
                $errors['username'] = $username;
                return redirect('/login')
                    ->withErrors($errors)
                    ->withInput($data);
            }

        }
    }

    //退出登录
    public function loginout(Request $request){
        $request->session()->forget('userid');
        $request->session()->forget('username');
       return redirect('/login')  ;
    }



    public function index()
    {
        return view('/admin/article/index');
       // return view('/admin/article/index');
    }
    //查看分类列表
    public function typelist(Request $request)
    {
        $data['data'] = ArticleTypeModel::paginate(10);
        $data['type'] = '3';
        return view('/admin/article/typelist',compact('data'));
    }
    //搜索分类
    public function searchTypeList(Request $request)
    {
        $id = $request->input('id');
        $type = $request->input('type');
        if($id == 1 || $type == 1) {
            $data['data'] = ArticleTypeModel::where(['pid' => 0])->paginate(10);
            $data['type'] = '1';
        } else {
            $data['data'] = ArticleTypeModel::whereNotIn('pid',[0])->paginate(10);
            $data['type'] = '2';
        }
        return view('/admin/article/typelist',compact('data'));
    }
    public function addtype()
    {
        return view('/admin/article/typeadd');
    }
    
    //展示excel详情
    public function showTypeExcel(Request $request)
    {
        if($request->isMethod('get')) {
            return redirect('/admin/addtype');
        } else if($request->isMethod('post')) {
            $data['type'] = $request->input('tstatus');
            $path = public_path('admin\\article\\uploads\\typeExcel');
            $res = fileUpload($request, 'typeexcel', $path, ['xls']);
            $temp = public_path('admin\\article\\uploads\\temp');
            $temp = $temp . '\\' . $res['msg'][1] . 'txt';
            if ($res['code'] == '1') {
                $result = Excel::load($res['msg'][0] . '\\' . $res['msg'][1], function ($reader) use ($temp) {
                    $reader = $reader->getSheet(0);
                    //获取excel表中的数据
                    $result = $reader->toArray();
                    file_put_contents($temp, json_encode($result));
                });
                $data['data'] = json_decode(file_get_contents($temp));
                unlink($res['msg'][0] . '\\' . $res['msg'][1]);
                unlink($temp);
                foreach ($data['data'] as $k => $v) {
                    $num = count($v);
                    if($num !== 2 || empty($v[0]) || empty($v[1])) {
                        return view('/admin/article/typeadd', ['error'=>'excel格式错误,请检查格式']);
                    }
                }
                return view('/admin/article/typeadd', compact('data'));
            } else {
                $username = $res['msg'];
                $errors['msg'] = $username;
                return redirect('/admin/addtype')
                    ->withErrors($errors);
            }
        }

    }

    //执行导入excel数据
    public function postTypeExcel(Request $request)
    {
        $data = $request->all();
        $str = rtrim($data['info'],'<br>');
        $str = preg_replace('/\t|\n| /', '', $str);
        $type_data = explode('<br>',$str);
        foreach ($type_data as $k => $v) {
            $v = rtrim($v,'-');
            $vv = explode('-',$v);
            $num = count($vv);
            if($num !== 2 || empty($vv[0]) || empty($vv[1])) {
                return response()->json(['status' => 500, 'msg' =>'格式错误']);
            }
        }
        foreach ($type_data as $k => $v) {
            $v = rtrim($v,'-');
            $vv = explode('-',$v);
            $num = count($vv);
            for ($i=0;$i<$num;$i++) {
                if($i == 0) {
                    $res = ArticleTypeModel::where(['status'=>$data['type'],'type'=>$vv[$i],'pid'=>$i])->first();
                    if(empty($res)) {
                       ArticleTypeModel::create(['type'=> $vv[$i],'status'=>$data['type']]);
                    }
                } else if($i == 1){
                    $res = ArticleTypeModel::where(['status'=>$data['type'],'type'=>$vv[$i-1],'pid'=>0])->first();
                    $newres = ArticleTypeModel::where(['status'=>$data['type'],'type'=>$vv[$i],'pid'=>$res->id])->first();
                    if(empty($newres)) {
                        $newres = ArticleTypeModel::create(['status'=>$data['type'],'type'=> $vv[$i],'pid'=>$res->id]);
                    }
                    session(['typepid'=>$newres->pid]);
                } else{
                    $res = ArticleTypeModel::where(['status'=>$data['type'],'type'=>$vv[$i-1],'pid'=>session('typepid')])->first();
                    $newres = ArticleTypeModel::where(['status'=>$data['type'],'type'=>$vv[$i],'pid'=>$res->id])->first();
                    if(empty($newres)) {
                      $newres = ArticleTypeModel::create(['status'=>$data['type'],'type'=> $vv[$i],'pid'=>$res->id]);
                    }
                    session(['typepid'=>$newres->pid]);
                }
            }
        }
        return response()->json(['status' => 200, 'msg' =>'导入结束']);
    }
    //删除分类
    public function deleteType(Request $request)
    {
        $id = $request->input('id');
        $res = ArticleTypeModel::where(['pid'=>$id])->first();
        $tres = TypeDetailModel::where(['tid'=>$id])->first();
        if(empty($res) || empty($tres)) {
            ArticleTypeModel::where(['id'=>$id])->delete();
            return response()->json(['status' => 200, 'msg' =>'删除成功']);
        }
        return response()->json(['status' => 500, 'msg' =>'删除失败']);
    }
    //编辑分类
    public function editType($id)
    {
        $data = ArticleTypeModel::where(['id' => $id])->first();
        return view('admin/article/typeedit', compact('data'));

    }

    //提交编辑
    public function postEditType(Request $request)
    {
        $data = $request->except(['_token','uploadfile']);
        $messages = [
            'required'   => '不能为空',
            'string'     => '格式错误',
        ];
        $validator = Validator::make($data, [
            'id'          => 'required|string',
            'type'        => 'required|string',

        ],$messages);
        if ($validator->fails()) {
            return redirect('/admin/editType/'.$data['id'])
                ->withErrors($validator)
                ->withInput($data);
        }
        if($request->hasFile('picture')) {
            $path = public_path('admin/article/uploads/type');
            $path2 = getSlash()."admin".getSlash()."article".getSlash()."uploads".getSlash()."type";
            $res = fileUpload($request, 'picture', $path, ['jpg', 'jpeg', 'png']);
            if ($res['code'] == '1') {
                $pic = ArticleTypeModel::select('picture')->where(['id'=>$data['id']])->first();
                $data['picture'] = $path2 . getSlash() . $res['msg'][1];
                if(!empty($pic->picture)) {
                    unlink(iconv("UTF-8","gb2312",getConversionUrl(public_path(ltrim($pic->picture, getSlash())))));
                }
            } else {
                $err = $res['msg'];
                $errors['picture'] = $err;
                return redirect('/admin/getProductEdit/'.$data['id'])
                    ->withErrors($errors)->withInput($data);
            }
        }
        ArticleTypeModel::where(['id'=>$data['id']])->update($data);
        return redirect('/admin/typelist');
    }
    //添加详情
    public function detailAdd(Request $request)
    {
        if($request->isMethod('get')) {
            $type = ArticleTypeModel::where(['pid' => 0])->get();
            return view('/admin/article/detailadd', compact('type'));
        } else {
            $data = $request->except(['_token','uploadfile','pid']);
            $messages = [
                'required'   => '不能为空',
                'string'     => '格式错误',
            ];
            $validator = Validator::make($data, [
                'tid'          => 'required|string',

            ],$messages);
            if ($validator->fails()) {
                return redirect('/admin/detailAdd/')
                    ->withErrors($validator);
            }
            $path = public_path('admin/article/uploads/detail');
            $path2 = getSlash()."admin".getSlash()."article".getSlash()."uploads".getSlash()."detail";
            $res = fileUpload($request, 'picture', $path, ['jpg', 'jpeg', 'png']);
            if ($res['code'] == '1') {
                $data['picture'] = $path2 . getSlash() . $res['msg'][1];
            } else {
                $err = $res['msg'];
                $errors['picture'] = $err;
                return redirect('/admin/detailAdd/')
                    ->withErrors($errors);
            }
            $detail = TypeDetailModel::where(['tid'=>$data['tid']])->first();
            if(empty($detail)) {
                TypeDetailModel::create($data);
            } else {
                 TypeDetailModel::where(['tid'=>$data['tid']])->update($data);
            }
            return redirect('/admin/detailList');
        }
    }
    //获取分类
    public function getType(Request $request)
    {
        $id = $request->input('id');
        if($id == '' || empty($id)) {
            return response()->json(['status' => 500, 'msg' =>'参数错误']);
        }
        $data = ArticleTypeModel::where(['pid'=>$id])->get();
        return response()->json(['status' => 200, 'msg' =>compact('data')]);
    }
    //获取分类列表
    public function detailList()
    {
        $data['tid'] = 1;
        $data['type'] = ArticleTypeModel::where(['pid'=>0])->get();
        $data['data'] = TypeDetailModel::select('show_type_detail.*','a.type')->join('show_article_type as a','a.id','=','show_type_detail.tid')->paginate(10);
        return view('/admin/article/detaillist',compact('data'));
    }
    //搜索分类列表
    public function searchDetailList(Request $request)
    {
        $id = $request->input('id');
        $pid = $request->input('pid');
        if(empty($id)){
            return redirect('/admin/detailList');
        }
        $data['tid'] = $id;
        $data['type'] = ArticleTypeModel::where(['pid'=>0])->get();
        if(!empty($pid)) {
            $data['childtype'] = ArticleTypeModel::where(['pid'=>$pid])->get();
        }
        $data['data'] = TypeDetailModel::select('show_type_detail.*','a.type')->join('show_article_type as a','a.id','=','show_type_detail.tid')->where(['show_type_detail.tid'=>$id])->paginate(10);
        return view('/admin/article/detaillist',compact('data'));
    }
    //获取详情编辑信息
    public function getEditDetail($id)
    {
        $data['data'] = TypeDetailModel::where(['id'=>$id])->first();
        $data['ptype'] = ArticleTypeModel::where(['id'=>$data['data']->tid])->first();
        $data['types'] = ArticleTypeModel::where(['pid'=>$data['ptype']->pid])->get();
        $data['type'] = ArticleTypeModel::where(['pid'=>0])->get();
        return view('/admin/article/detailedit',compact('data'));
    }
   //修改详情
    public function postDetaiEdit(Request $request)
    {

        $data = $request->except(['_token','uploadfile']);
        $messages = [
            'required'   => '不能为空',
            'string'     => '格式错误',
        ];
        $validator = Validator::make($data, [
            'tid'          => 'required|string',

        ],$messages);
        if ($validator->fails()) {
            return redirect('/admin/getEditDetail/'.$data['id'])
                ->withErrors($validator)
                ->withInput($data);
        }
        if($request->hasFile('picture')) {
            $path = public_path('admin/article/uploads/detail');
            $path2 = getSlash()."admin".getSlash()."article".getSlash()."uploads".getSlash()."detail";
            $res = fileUpload($request, 'picture', $path, ['jpg', 'jpeg', 'png']);
            if ($res['code'] == '1') {
                $pic = TypeDetailModel::select('picture')->where(['id'=>$data['id']])->first();
                $data['picture'] = $path2 . getSlash() . $res['msg'][1];
                if(!empty($pic->picture)) {
                    unlink(iconv("UTF-8","gb2312",getConversionUrl(public_path(ltrim($pic->picture, getSlash())))));
                }
            } else {
                $err = $res['msg'];
                $errors['picture'] = $err;
                return redirect('/admin/getEditDetail/'.$data['id'])
                    ->withErrors($errors)->withInput($data);
            }
        }
        TypeDetailModel::where(['id'=>$data['id']])->update($data);
        return redirect('/admin/detailList');
    }
    //删除详情
    public function deleteDetail(Request $request)
    {
        $id = $request->input('id');
        $res = TypeDetailModel::where(['id'=>$id])->first();
        if(!empty($res)) {
            TypeDetailModel::where(['id'=>$id])->delete();
            unlink(getConversionUrl(public_path(ltrim($res->picture, getSlash()))));
            return response()->json(['status' => 200, 'msg' =>'删除成功']);
        }
        return response()->json(['status' => 500, 'msg' =>'删除失败']);
    }
}
